/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gitee.fdc.mapper;

import com.gitee.fdc.base.mapper.logicdelete.DeleteLogic;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import tk.mybatis.mapper.annotation.Version;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.SqlHelper;
import static tk.mybatis.mapper.mapperhelper.SqlHelper.getIfNotNull;
import tk.mybatis.mapper.version.VersionException;

/**
 *
 * @author qskj
 */
public class SbbsSqlHelper {

    /**
     * update set列
     *
     * @param entityClass
     * @param entityName 实体映射名
     * @param notNull 是否判断!=null
     * @param notEmpty 是否判断String类型!=''
     * @return
     */
    public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty, boolean dealDelFlag) {
        StringBuilder sql = new StringBuilder();
        sql.append("<set>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //对乐观锁的支持
        EntityColumn versionColumn = null;
        EntityColumn deleteLogicColumn = findDeleteLogicColumn(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            if (column.getEntityField().isAnnotationPresent(Version.class)) {
                if (versionColumn != null) {
                    throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                versionColumn = column;
            }

            if (!column.isId() && column.isUpdatable()) {
                if (column == versionColumn) {
                    Version version = versionColumn.getEntityField().getAnnotation(Version.class);
                    String versionClass = version.nextVersion().getCanonicalName();
                    //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)}
                    sql.append(column.getColumn())
                            .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(")
                            .append("@").append(versionClass).append("@class, ")
                            .append(column.getProperty()).append(")},");
                } else if (column == deleteLogicColumn && dealDelFlag) {
                    //什么也不做
//                    sql.append(column.getColumn()).append("=1");
                    sql.append(column.getColumnEqualsHolder(entityName) + ",");

                } else if (notNull) {
                    sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty));
                } else {
                    sql.append(column.getColumnEqualsHolder(entityName) + ",");
                }
            } else if (column.isId() && column.isUpdatable()) {
                //set id = id,
                sql.append(column.getColumn()).append(" = ").append(column.getColumn()).append(",");
            }
        }
        sql.append("</set>");
        return sql.toString();
    }

    public static String updateDeleteLogicColumn(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty, boolean unDelete) {
        StringBuilder sql = new StringBuilder();
        sql.append("<set>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //对乐观锁的支持
        EntityColumn versionColumn = null;
        EntityColumn deleteLogicColumn = findDeleteLogicColumn(entityClass);

        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            if (column.getEntityField().isAnnotationPresent(Version.class)) {
                if (versionColumn != null) {
                    throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                versionColumn = column;
            }

            if (!column.isId() && column.isUpdatable()) {
                if (column == versionColumn) {
                    Version version = versionColumn.getEntityField().getAnnotation(Version.class);
                    String versionClass = version.nextVersion().getCanonicalName();
                    //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)}
                    sql.append(column.getColumn())
                            .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(")
                            .append("@").append(versionClass).append("@class, ")
                            .append(column.getProperty()).append(")},");
                } else if (column == deleteLogicColumn) {
                    sql.append(column.getColumn());
                    if (!unDelete) {
                        sql.append("=1");
                    } else {
                        sql.append("=0");
                    }
                }
            } else if (column.isId() && column.isUpdatable()) {
                //set id = id,
                sql.append(column.getColumn()).append(" = ").append(column.getColumn()).append(",");
            }
        }
        sql.append("</set>");
        return sql.toString();
    }

    /**
     * where所有列的条件，会判断是否!=null
     *
     * @param entityClass
     * @param empty
     * @return
     */
    public static String whereAllIfColumns(Class<?> entityClass, boolean empty) {
        return whereAllIfColumns(entityClass, empty, false);
    }

    /**
     * where所有列的条件，会判断是否!=null
     *
     * @param entityClass
     * @param empty
     * @param useVersion
     * @return
     */
    public static String whereAllIfColumns(Class<?> entityClass, boolean empty, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        EntityColumn deleteLogicColumn = findDeleteLogicColumn(entityClass);
        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) {
                sql.append(getIfNotNull(column, " AND " + column.getColumnEqualsHolder(), empty));
            }

        }
        if (useVersion) {
            sql.append(whereVersion(entityClass));
        }
        if (deleteLogicColumn != null) {
//            sql.append(whereVersion(entityClass));
            sql.append(" AND ").append(deleteLogicColumn.getColumn()).append("=0");
        }

        sql.append("</where>");
        return sql.toString();
    }

    public static String whereSelectAllIfDeleteLogic(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        EntityColumn deleteLogicColumn = findDeleteLogicColumn(entityClass);
        sql.append("<where>");
        if (deleteLogicColumn != null) {
            sql.append(deleteLogicColumn.getColumn()).append("=0");
        } else {
            sql.append(" 1=1 ");

        }

        sql.append("</where>");
        return sql.toString();
    }

    /**
     * 乐观锁字段条件
     *
     * @param entityClass
     * @return
     */
    public static String whereVersion(Class<?> entityClass) {
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        boolean hasVersion = false;
        String result = "";
        for (EntityColumn column : columnSet) {
            if (column.getEntityField().isAnnotationPresent(Version.class)) {
                if (hasVersion) {
                    throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                hasVersion = true;
                result = " AND " + column.getColumnEqualsHolder();
            }
        }
        return result;
    }

    /**
     * where主键条件 不使用version，不查已删除的
     *
     * @param entityClass
     * @return
     */
    public static String wherePKColumns(Class<?> entityClass) {
        return wherePKColumns(entityClass, false, false);
    }

    /**
     * where主键条件 不使用version，按需查已删除的：true不查，false 查
     *
     * @param entityClass
     * @return
     */
    public static String wherePKColumns(Class<?> entityClass, boolean delFlag) {
        return wherePKColumns(entityClass, false, delFlag);
    }

    /**
     * where主键条件
     *
     * @param entityClass
     * @param useVersion 是否使用version
     * @param delFlag
     * @return
     */
    public static String wherePKColumns(Class<?> entityClass, boolean useVersion, boolean delFlag) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        EntityColumn deleteLogicColumn = findDeleteLogicColumn(entityClass);

        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            sql.append(" AND " + column.getColumnEqualsHolder());
        }
        if (useVersion) {
            sql.append(whereVersion(entityClass));
        }

        if (deleteLogicColumn != null && !delFlag) {
            sql.append(" AND ").append(deleteLogicColumn.getColumn()).append("=0");
        }
        sql.append("</where>");
        return sql.toString();
    }

    private static final Map<Class<?>, EntityColumn> entityDeleltLogicColumnMap = new HashMap<Class<?>, EntityColumn>();

    public static EntityColumn findDeleteLogicColumn(Class<?> entityClass) {

        boolean hasClass = entityDeleltLogicColumnMap.containsKey(entityClass);
        if (hasClass) {
            return entityDeleltLogicColumnMap.get(entityClass);
        } else {
            EntityColumn deleteLogicColumn = null;
            Set<EntityColumn> allColumnSet = EntityHelper.getColumns(entityClass);
            for (EntityColumn column : allColumnSet) {
                if (column.getEntityField().isAnnotationPresent(DeleteLogic.class)) {
                    if (deleteLogicColumn != null) {
                        throw new VersionException(entityClass.getCanonicalName() + " 中包含多个带有 @DeleteLogic 注解的字段，一个类中只能存在一个带有 @DeleteLogic 注解的字段!");
                    }
                    deleteLogicColumn = column;
                    break;
                }
            }
            entityDeleltLogicColumnMap.put(entityClass, deleteLogicColumn);
            return deleteLogicColumn;
        }

    }
}
